#!/usr/bin/env python

import sip
from startline import StartLine as _sl_startline
from headerutils import HeaderList as _hu_hlist
from voipy.utils import StringBuf as _p_strbuf
from voipy.utils import ParsingString as _p_pstr

# => Headers() container object...

class Message(sip.SIP):
    sep = '\r\n'

    startline = ''
    headers = None
    body = ''

    def __init__(self, *args, **kwargs):
        self.startline = _sl_startline()
        self.headers = _hu_hlist()
        super(Message, self).__init__(*args, **kwargs)

    def parse(self, buf):
        str = _p_strbuf(buf)

        def get_start_line():
            return str.readline()
        def get_headers():
            import header

            hl = []; cl = ""
            while 1:
                l = str.readline().strip()
                if not len(l): break
                if cl: cl += ' '
                cl += l

                if len(buf) == str.tell(): break

                if buf[str.tell()] in [' ', '\t']:
                    continue

                hl.append( _p_pstr( cl ) )
                cl = ''
            return [ header.Header(h) for h in hl ]

        def get_body():
            return str.read()

        self.startline.parse( get_start_line() )
        self.headers.update( get_headers() )
        self.body = get_body()

    def __iaddr__(self, other):
        # XXX check for list type here
        self.headers += header.Header( other )
        return self

    def __str__(self):
        return self.sep.join(
                [str(self.startline)] +
                [str(hdr) for hdr in self.headers] +
                [''] +
                [str(self.body)]
            )
